package com.yimi.yinhepda.views.dispatch_module;

import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.pda.ym.entity.response.NoDataResponse;
import com.yimi.yinhepda.R;
import com.yimi.yinhepda.adapter.DeleteByHandAdapter;
import com.pda.ym.callbacks.UICallBack;
import com.yimi.yinhepda.db.dao.DispactchScanTableDao;
import com.yimi.yinhepda.db.table.DispatchScanTable;
import com.yimi.yinhepda.entity.bean.DeleteEntity;
import com.yimi.yinhepda.entity.bean.DispatchEntity;
import com.yimi.yinhepda.entity.request.DispatchDeleteRequest;
import com.yimi.yinhepda.entity.response.DispatchScanResponse;
import com.yimi.yinhepda.event.CountEvent;
import com.pda.ym.net.NetRequest;
import com.pda.ym.utils.Constants;
import com.yimi.yinhepda.utils.IntentUtils;
import com.pda.ym.utils.SoundVibratorManager;
import com.pda.ym.utils.StringUtils;
import com.yimi.yinhepda.base.BaseInitActivity;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import butterknife.Bind;

/**
 * @author 000432
 * @date 2017/4/22 0022
 *
 * 手动撤销
 */
public class DispatchDeleteByHandActivity extends BaseInitActivity {
  /** 标题栏左边 */
  @Bind(R.id.title) TextView mTvTitle;
  /** 标题栏中间 */
  @Bind(R.id.num) TextView mTvNum;
  /** 添加按钮 */
  @Bind(R.id.manual_delete_btn) Button mBtnDelete;
  /** 条码输入框 */
  @Bind(R.id.load_addchildwaybill_ed) EditText mEtBarcode;
  @Bind(R.id.add_chidlwaybill_listview) ListView mListView;
  @Bind(R.id.manaul_delete_count) TextView mTvDeleteTip;
  @Bind(R.id.add_childwaybill_back) ImageView mImgAddBack;
  @Bind(R.id.add_childwaybill_ok) ImageView mImgAddOk;

  private DispactchScanTableDao mDispactchScanTableDao;
  private List<DeleteEntity> mDeleteEntityList = new ArrayList<>();
  private DeleteByHandAdapter mAdapter;
  /** 手加票 */
  private int mHandDeleteBill;
  /** 手加件 */
  private int mHandDeleteItem;
  /** 建包目的地 */
  private String destCode;
  private String destName;
  private String mTaskNo;
  /** 总的未上传数量 */
  private int totalNotUploadNum;

  /** 派送任务集合 */
  private List<DispatchEntity> mDispatchDataList;

  @Override public String getPageName() {
    return getString(R.string.page_dispatch_addbydelete);
  }

  public DispatchDeleteByHandActivity() {
    super(true);
  }

  @Override public int getContentViewId() {
    return R.layout.activity_delete_childbillway;
  }

  @Override public void initView(Bundle savedInstanceState) {
    mTvTitle.setText(getString(R.string.hand_delete_title));
  }

  @Override public void initEvent() {
    mBtnDelete.setOnClickListener(this);
    mImgAddBack.setOnClickListener(this);
    mImgAddOk.setOnClickListener(this);
  }

  @Override public void initData() {
    //目的地
    destCode = getIntent().getStringExtra(IntentUtils.BUILD_DEST);
    destName = getIntent().getStringExtra(IntentUtils.BUILD_DEST_NAME);
    mTaskNo = getIntent().getStringExtra("taskno");
    mDispatchDataList = DispatchScanActivity.mDispatchDataList;
    //数据库对象
    mDispactchScanTableDao = new DispactchScanTableDao();
    totalNotUploadNum = mDispactchScanTableDao.queryNotUploadDataNum();
    mTvNum.setText(totalNotUploadNum + "");

    //列表
    mAdapter = new DeleteByHandAdapter(this, mDeleteEntityList);
    mListView.setAdapter(mAdapter);
  }

  @Override public void onClick(View v) {
    super.onClick(v);

    switch (v.getId()) {
      //撤销按钮
      case R.id.manual_delete_btn:
        startDeleteBarData();
        break;
      //返回按钮
      case R.id.add_childwaybill_back:
        activityBackMethod();
        break;
      case R.id.add_childwaybill_ok:
        //确定按钮
        activityBackMethod();
        break;
      default:
        break;
    }
  }

  @Override protected void handleBarCode(String result) {
    super.handleBarCode(result);
    if (result == null) {
      SoundVibratorManager.playSound(2);
      showToast("运单号扫描失败");
    } else {
      mEtBarcode.setText(result);
    }
  }

  /**
   * 开始添加条码的操作
   */
  private void startDeleteBarData() {

    String barCodeStr = mEtBarcode.getText().toString().trim();
    if (!StringUtils.isWaybillNo(barCodeStr)) {
      showToast("运单号不规范!");
      SoundVibratorManager.playSound(2);
      return;
    }

    /***
     * buildList 是扫描页面全局的
     */
    if (mDispatchDataList == null) {
      return;
    }
    for (int i = 0; i < mDispatchDataList.size(); i++) {

      //当前行的运单信息，包括子单的集合
      DispatchEntity currentItemInfo = mDispatchDataList.get(i);
      /** 判断子单是不是以主单开始的,减少循环次数*/
      if (!barCodeStr.startsWith(String.valueOf(currentItemInfo.getWaybillNo()))) {
        continue;
      }
      //子单的集合
      List<DispatchScanResponse.DispatchWaybillChild> childList = currentItemInfo.getChildList();
      //循环子单的集合
      if (childList != null) {
        for (DispatchScanResponse.DispatchWaybillChild child : childList) {
          //子单字符串
          String childWaybillno = child.getChildNo();
          //扫描子单和集合中一个子单相同
          if (barCodeStr.equals(childWaybillno)) {
            Integer flag = child.getFlag();
            if (flag == 0) {
              SoundVibratorManager.playSound(2);
              showToast("该条码还未扫描!");
            } else if (flag == 1) {
              //通过接口撤销
              List<DispatchScanTable> mChildList =
                  mDispactchScanTableDao.findDataByChildNo(currentItemInfo.getWaybillNo(), child.getChildNo(), mTaskNo);
              if (mChildList == null || mChildList.size() <= 0) {
                showToast("该条码还未扫描!");
                return;
              }
              deleteDispatchTaskByPDA(mChildList.get(0), currentItemInfo, child, i);
            }
            return;
          }
        }
      }
    }

    //该条码不在配载单据内
    SoundVibratorManager.playSound(2);
    showToast(getString(R.string.num_no_in_task_list));
  }

  /***
   * 通过接口撤销
   */
  private void deleteDispatchTaskByPDA(DispatchScanTable itemTable, final DispatchEntity currentItemInfo,
      final DispatchScanResponse.DispatchWaybillChild childItem, final int position) {
    //关闭扫描
    setScannerEnabled(false);
    showPgDlg("正在撤销扫描数据...");

    DispatchDeleteRequest dispatchDeleteRequest = new DispatchDeleteRequest();
    //主单
    dispatchDeleteRequest.setWaybillNo(itemTable.getWaybillNo());
    //子单
    dispatchDeleteRequest.setChildNo(itemTable.getChildNo());
    dispatchDeleteRequest.setScanEmpCode(itemTable.getScanEmpCode());
    //强扫
    dispatchDeleteRequest.setChildRemark(itemTable.getChildRemark());
    dispatchDeleteRequest.setDispatchArea(itemTable.getDispatchArea());
    dispatchDeleteRequest.setInputType(itemTable.getInputType());
    dispatchDeleteRequest.setSacnDeptCode(itemTable.getSacnDeptCode());
    // 扫描的时间
    dispatchDeleteRequest.setSacnTime(itemTable.getScanTime());
    //配置单号
    dispatchDeleteRequest.setTaskNo(itemTable.getTaskNo());
    dispatchDeleteRequest.setUserIp(itemTable.getUserIp());

    new NetRequest().setMethod(NetRequest.Method.POST_STRING)
        .setRequestObject(dispatchDeleteRequest)
        .setResponsClazz(NoDataResponse.class)
        .setUrl(Constants.URL_DISPATCH_DELETE)
        .execute(new UICallBack() {
          @Override public void onError(String msg) {
            //开启扫描
            setScannerEnabled(true);
            dismissPgDlg();
            SoundVibratorManager.playSound(2);
            if (msg != null) {
              showToast("撤销失败:" + msg);
            } else {
              showToast("撤销失败!");
            }
          }

          @Override public void onSuccess(Object obj) {
            /** 扫描数据删除从表中*/
            if (deleteScannedData(childItem) < 0) {
              SoundVibratorManager.playSound(2);
              showToast("插入数据库失败!");
              return;
            }

            totalNotUploadNum--;
            mTvNum.setText(totalNotUploadNum + "");
            EventBus.getDefault().post(new CountEvent(totalNotUploadNum));

            /** 为未扫描的状态*/
            childItem.setFlag(0);

            /** 查询数据库中当前运单下的已经扫描的数量*/
            int scannedNum = mDispactchScanTableDao.getScannedDataList(childItem.getWaybillNO() + "");

            boolean isChanged = false;
            /** 列表中已经有对应运单号的撤销，加一个就好，如果没有加新的一行*/
            if (mDeleteEntityList != null) {
              for (int j = 0; j < mDeleteEntityList.size(); j++) {
                DeleteEntity deleteEntity = mDeleteEntityList.get(j);
                //扫描的子单对应运单号在列表已经有了，撤销数量加1就好
                if (deleteEntity.getWayBillNo().equals(childItem.getWaybillNO() + "")) {
                  deleteEntity.setDeleteNum(deleteEntity.getDeleteNum() + 1);
                  deleteEntity.setScannedNum(scannedNum);
                  mAdapter.notifyDataSetChanged();
                  isChanged = true;
                  break;
                }
              }
            }
            /***
             * 之前没有撤销过的单子，自己添加一行到列表
             */
            if (!isChanged) {
              DeleteEntity deleteEntity = new DeleteEntity();
              deleteEntity.setWayBillNo(childItem.getWaybillNO() + "");
              deleteEntity.setScannedNum(scannedNum);
              deleteEntity.setDeleteNum(1);
              mDeleteEntityList.add(deleteEntity);
              mAdapter.notifyDataSetChanged();
            }

            /** 刷新手动撤销的票和件*/
            mHandDeleteBill = getHandDeleteBill();
            mHandDeleteItem++;
            mTvDeleteTip.setText(String.format(getString(R.string.hand_delete_num), mHandDeleteBill, mHandDeleteItem));

            /** 更新当前行到第一行*/
            mDispatchDataList.remove(position);
            mDispatchDataList.add(0, currentItemInfo);

            //开启扫描
            setScannerEnabled(true);
            dismissPgDlg();
            SoundVibratorManager.playSound(1);
          }
        });
  }

  /**
   * 手动添加的票数
   */
  private int getHandDeleteBill() {
    Set<String> set = new HashSet<String>();
    for (DeleteEntity item : mDeleteEntityList) {
      set.add(item.getWayBillNo());
    }
    return set.size();
  }

  /**
   * 删除已经扫描的数据到表中
   *
   * @param child 当前子单的相关信息
   */
  private int deleteScannedData(DispatchScanResponse.DispatchWaybillChild child) {
    int result = 0;
    try {
      result = mDispactchScanTableDao.delelteByChildBill(child.getChildNo());
      Log.d("tag", "deleteScannedData: result=" + result);
    } catch (Exception e) {
      e.printStackTrace();
      result = -1;
    }
    return result;
  }

  @Override public boolean onKeyDown(int keyCode, KeyEvent event) {
    if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
      activityBackMethod();
    }
    return false;
  }

  private void activityBackMethod() {
    finish();
  }
}
